package com.hqd.ch03.v26.factory.support;

import com.hqd.ch03.v26.beans.Mergeable;

import java.util.Properties;

public class ManagedProperties extends Properties implements Mergeable {

    private boolean mergeEnabled;

    @Override
    public boolean isMergeEnabled() {
        return this.mergeEnabled;
    }

    public void setMergeEnabled(boolean mergeEnabled) {
        this.mergeEnabled = mergeEnabled;
    }

    @Override
    public Object merge(Object parent) {
        if (!this.mergeEnabled) {
            throw new IllegalStateException("Not allowed to merge when the 'mergeEnabled' property is set to 'false'");
        }
        if (parent == null) {
            return this;
        }
        if (!(parent instanceof Properties)) {
            throw new IllegalArgumentException("Cannot merge with object of type [" + parent.getClass() + "]");
        }
        Properties merged = new ManagedProperties();
        merged.putAll((Properties) parent);
        merged.putAll(this);
        return merged;
    }

}
